package com.weiyin.examination.course;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.weiyin.examination.R;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.application.ResId;
import com.weiyin.examination.dialog.CourseDialog;
import com.weiyin.examination.dialog.FlatSharpDialog;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogResultInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.CourseA2Module;
import com.weiyin.examination.module.SelectionModule;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.util.ScreenUtil;
import com.weiyin.examination.view.CourseView;
import com.weiyin.examination.view.RoundProgressBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author njf
 *         Created by lenovo on 2017/9/18.
 */

public class CourseA2 extends Course {
    private static final int HEIGHT = 80;
    private static final int WIDTH = 300;
    private View rootView, courseA2View1, courseA2View2, courseA2View3, courseA2View4, oldView,
            courseA2Shape1, courseA2Shape2, courseA2Shape3, courseA2Shape4;
    private Activity activity;
    private ClickAble clickAble;
    private TouchAble touchAble;

    private TextView titleLayoutNextTextView, titleLayoutLastTextView, titleLayoutSubjectContentTextView,
            titleLayoutSubjectScoreTextView, titleLayoutNumberTextView, titleTicketNumber;
    private RelativeLayout titleLayoutNumberRl;
    private ImageView courseA2FlatSharp, courseA2ImageView1, courseA2ImageView2, courseA2ImageView3, courseA2ImageView4, courseA2LayoutPlay;
    private CourseView courseA2PDFView, courseA2PDFView1;

    private RoundProgressBar course1LayoutProgressBar;
    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private List<ImageView> imageViews;
    private MediaPlayer mediaPlayer;
    private AnimationDrawable backtabAnimation;

    private int mediaIndex = 0, courseIndex, stopIndex = 0;
    private Handler mHandler = new Handler();

    private int answerPosition = 0, oldIndex = 0;
    LayoutHelper layoutHelper;

    private ResId resId;
    private boolean clef = true;

    private List<CourseA2Module> regionList;
    private List<Boolean> moveList;
    private int moveIndex = 100;
    private CourseDialog courseDialog;
    private int viewId;
    private Map<String, String> map = new HashMap<>();

    private double score;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.coursea2_layout, null);

            layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);

            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            this.testModule = testModuleList.get(index);
            clickAble = new ClickAble();
            touchAble = new TouchAble();
            resId = new ResId();
            mediaPlayer = new MediaPlayer();
            regionList = new ArrayList<>();
            imageViews = new ArrayList<>();
            moveList = new ArrayList<>();
            if (testModule != null) {
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                }
            }
            initView();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView() {
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        courseA2PDFView = (CourseView) rootView.findViewById(R.id.courseA2PDFView);
        courseA2ImageView1 = (ImageView) rootView.findViewById(R.id.courseA2ImageView1);
        courseA2ImageView2 = (ImageView) rootView.findViewById(R.id.courseA2ImageView2);
        courseA2ImageView3 = (ImageView) rootView.findViewById(R.id.courseA2ImageView3);
        courseA2ImageView4 = (ImageView) rootView.findViewById(R.id.courseA2ImageView4);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);
        courseA2PDFView1 = (CourseView) rootView.findViewById(R.id.courseA2PDFView1);
        courseA2FlatSharp = (ImageView) rootView.findViewById(R.id.courseA2FlatSharp);

        imageViews.add(courseA2ImageView1);
        imageViews.add(courseA2ImageView2);
        imageViews.add(courseA2ImageView3);
        imageViews.add(courseA2ImageView4);

        courseA2Shape1 = rootView.findViewById(R.id.courseA2Shape1);
        courseA2Shape2 = rootView.findViewById(R.id.courseA2Shape2);
        courseA2Shape3 = rootView.findViewById(R.id.courseA2Shape3);
        courseA2Shape4 = rootView.findViewById(R.id.courseA2Shape4);

        courseA2View1 = rootView.findViewById(R.id.courseA2View1);
        courseA2View2 = rootView.findViewById(R.id.courseA2View2);
        courseA2View3 = rootView.findViewById(R.id.courseA2View3);
        courseA2View4 = rootView.findViewById(R.id.courseA2View4);


        courseA2ImageView1.setOnTouchListener(touchAble);
        courseA2ImageView2.setOnTouchListener(touchAble);
        courseA2ImageView3.setOnTouchListener(touchAble);
        courseA2ImageView4.setOnTouchListener(touchAble);
        courseA2FlatSharp.setOnClickListener(clickAble);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);

        course1LayoutProgressBar = (RoundProgressBar) rootView.findViewById(R.id.courseA2LayoutProgressBar);
        courseA2LayoutPlay = (ImageView) rootView.findViewById(R.id.courseA2LayoutPlay);

        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);
        courseA2PDFView.setHeight(300);
        courseA2PDFView.setTerminate(false);
        courseA2PDFView1.setHeight(300);
        courseA2PDFView.setCourseA2(true);
        courseA2PDFView1.setCourseA2(true);
    }

    @SuppressLint("SetTextI18n")
    private void initViewData() {
        if (testModule != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (stopIndex < Constant.MEDIA_PLAYER_STOP_NUMBER && mediaIndex < testModule.getMp3UrlList().size()) {
                        mediaPlayerPlay();
                        mHandler.removeCallbacks(this);
                    }
                    LogUtil.i(TAG, "courseA2PDFView.getTop()=" + courseA2PDFView.getTop() + " courseA2PDFView1.getTop()=" + courseA2PDFView1.getTop());
                }
            }, 1000);


            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());

            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);
            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶" + testModule.getSubjectTitle());
            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");

            for (int i = 0; i < testModule.getSelectionList().size(); i++) {
                SelectionModule selectionModule = testModule.getSelectionList().get(i);
                if (i < imageViews.size()) {
                    if (selectionModule != null) {
                        Glide.with(activity).
                                load(RetrofitClient.BASE_URL + selectionModule.getImageUrl()).
                                into(imageViews.get(i));
                    }
                }
            }
        }
    }

    private class TouchAble implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    //按下时记住x,y的坐标
                    courseA2Shape1.setVisibility(View.VISIBLE);
                    courseA2Shape2.setVisibility(View.VISIBLE);
                    courseA2Shape3.setVisibility(View.VISIBLE);
                    courseA2Shape4.setVisibility(View.VISIBLE);

                    for (int i = 0; i < regionList.size(); i++) {
                        Region region = regionList.get(i).getRegion();
                        if (region.contains((int) v.getX(), (int) v.getY())) {
                            moveIndex = i;
                            if (moveList.size() > moveIndex) {
                                LogUtil.i(TAG, "moveIndex=" + moveIndex + "  false");
                                moveList.set(moveIndex, false);
                            }
                        }
                    }
                    switch (v.getId()) {
                        case R.id.courseA2ImageView1:
                            oldView = courseA2View1;
                            break;
                        case R.id.courseA2ImageView2:
                            oldView = courseA2View2;
                            break;
                        case R.id.courseA2ImageView3:
                            oldView = courseA2View3;
                            break;
                        case R.id.courseA2ImageView4:
                            oldView = courseA2View4;
                            break;
                        default:
                            break;
                    }
                    oldView.setAlpha(0.4f);
                    break;
                case MotionEvent.ACTION_MOVE:
                    //移动时 用另一个模型记住按下时的位置
                    move(v, event);
                    break;
                case MotionEvent.ACTION_UP:
                    actionUp(v, event);
                    courseA2Shape1.setVisibility(View.GONE);
                    courseA2Shape2.setVisibility(View.GONE);
                    courseA2Shape3.setVisibility(View.GONE);
                    courseA2Shape4.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void move(View v, MotionEvent event) {
        LogUtil.i(TAG, event.getRawX() + "  " + event.getRawY() + " width=" + v.getWidth() + " height=" + v.getHeight() + " " + ScreenUtil.getScreenWidth(activity.getApplicationContext()));
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(v.getWidth(), v.getHeight());
        int maxWidth = ScreenUtil.getScreenWidth(activity.getApplicationContext());
        if (event.getRawX() + v.getWidth() / 2 < maxWidth) {
            layoutParams.leftMargin = (int) event.getRawX() - v.getWidth() / 2;
        } else {
            layoutParams.leftMargin = maxWidth - v.getWidth();
        }
        layoutParams.topMargin = (int) event.getRawY() - v.getHeight() * 2;
        v.setLayoutParams(layoutParams);
        LogUtil.i(TAG, event.getRawX() + "  " + event.getRawY() + " width=" + v.getWidth() + " height=" + v.getHeight());
        LogUtil.i(TAG, "v.getBottom()=" + v.getBottom() + " courseA2PDFView.getBottom()=" + courseA2PDFView.getBottom() + " courseA2PDFView.getTop()=" + courseA2PDFView.getTop());
    }

    private void actionUp(View v, MotionEvent event) {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(v.getWidth(), v.getHeight());
//        if (v.getBottom() < courseA2PDFView.getBottom() + 10 && v.getBottom() - 60 > courseA2PDFView.getTop()) {
//            int maxWidth = ScreenUtil.getScreenWidth(activity.getApplicationContext());
//            if (event.getRawX() + v.getWidth() / 2 < maxWidth) {
//                layoutParams.leftMargin = (int) event.getRawX() - v.getWidth() / 2;
//            } else {
//                layoutParams.leftMargin = maxWidth - v.getWidth();
//            }
//            layoutParams.topMargin =;
//            LogUtil.i(TAG, "courseA2PDFView.getBottom()=" + courseA2PDFView.getBottom() + "v.getHeight()=" + v.getHeight());
//            answerPosition++;
//        } else {
//            layoutParams.topMargin = oldView.getTop();
//            layoutParams.leftMargin = oldView.getLeft();
//            oldView.setAlpha(1.0f);
//            answerPosition--;
//        }
        boolean update = false;
        for (int i = 0; i < regionList.size(); i++) {
            Region region = regionList.get(i).getRegion();
            LogUtil.i(TAG, "v.getX()=" + v.getX() + " v.getY()=" + v.getY() +
                    " regionList.get(i).getRectF().left=" + regionList.get(i).getRectF().left +
                    " regionList.get(i).getRectF().bottom=" + regionList.get(i).getRectF().bottom +
                    " regionList.get(i).getRectF().top=" + regionList.get(i).getRectF().top +
                    " regionList.get(i).getRectF().right=" + regionList.get(i).getRectF().right);
            if (region.contains((int) v.getX(), (int) v.getY()) && !moveList.get(i)) {
                LogUtil.i(TAG, "moveIndex=" + i + "  true");
                moveList.set(i, true);
                layoutParams.leftMargin = (int) regionList.get(i).getRectF().left;
                layoutParams.topMargin = (int) regionList.get(i).getRectF().bottom;
                update = true;
                answerPosition++;

                for (int j = 0; j < imageViews.size(); j++) {
                    if (v == imageViews.get(j)) {
                        map.put(i + "", testModule.getSelectionList().get(j).getId());
                    }
                }
            }
        }
        if (!update) {
            layoutParams.topMargin = oldView.getTop();
            layoutParams.leftMargin = oldView.getLeft();
            oldView.setAlpha(1.0f);
            if (oldView == courseA2View1) {
                map.put(0 + "", "-1");
            } else if (oldView == courseA2View2) {
                map.put(1 + "", "-1");
            } else if (oldView == courseA2View3) {
                map.put(2 + "", "-1");
            } else if (oldView == courseA2View3) {
                map.put(3 + "", "-1");
            }
            answerPosition--;
        }
        v.setLayoutParams(layoutParams);
    }

    private void showFlatSharpDialog(final ImageView view, boolean type) {
        FlatSharpDialog flatSharpDialog = new FlatSharpDialog(activity, R.style.base_loading_dialogfragment, type, "1");
        Window window = flatSharpDialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams p = window.getAttributes();
        Display d = window.getWindowManager().getDefaultDisplay();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        // 新位置X坐标
        p.x = location[0] - view.getWidth() / 2;
        // 新位置Y坐标
        p.y = location[1];
        window.setAttributes(p);
        flatSharpDialog.show();
        flatSharpDialog.setDialogResultInterface(new DialogResultInterface() {
            @Override
            public void result(String type, String result, String answerId) {
                if (Constant.COURSE_A9_DIALOG_RESULT2.equals(type)) {
                    int index = Integer.valueOf(result);
                    view.setImageResource(resId.getTimeImageId1()[Integer.valueOf(result)]);
                    if (regionList != null) {
                        regionList.clear();
                    }
                    assert regionList != null;
                    LogUtil.i(TAG, "INDEX=" + index + " regionList.size=" + regionList.size());
                    assert moveList != null;
                    if (moveList.size() > 0) {
                        moveList.clear();
                    }
                    if (index == 3) {
                        if (oldIndex != 3 && oldIndex != 0) {
                            reduction();
                        }
                        int y = courseA2PDFView.getTop() + courseA2ImageView1.getHeight() - layoutHelper.scaleDimension(40, "y");
                        Region region = new Region(courseA2View1.getLeft(), y - courseA2ImageView1.getHeight(), courseA2View1.getRight(), y + HEIGHT * 2);
                        Region region1 = new Region(courseA2View2.getLeft(), y - courseA2ImageView2.getHeight(), courseA2View2.getRight(), y + HEIGHT * 2);
                        Region region2 = new Region(courseA2View3.getLeft(), y - courseA2ImageView3.getHeight(), courseA2View3.getRight(), y + HEIGHT * 2);
                        Region region3 = new Region(courseA2View4.getLeft(), y - courseA2ImageView4.getHeight(), courseA2View4.getRight(), y + HEIGHT * 2);

                        CourseA2Module courseA2Module = new CourseA2Module(region, new RectF(courseA2View1.getLeft(), y - courseA2ImageView1.getHeight(), courseA2View1.getRight(), y));
                        CourseA2Module courseA2Module1 = new CourseA2Module(region1, new RectF(courseA2View2.getLeft(), y - courseA2ImageView2.getHeight(), courseA2View2.getRight(), y));
                        CourseA2Module courseA2Module2 = new CourseA2Module(region2, new RectF(courseA2View3.getLeft(), y - courseA2ImageView3.getHeight(), courseA2View3.getRight(), y));
                        CourseA2Module courseA2Module3 = new CourseA2Module(region3, new RectF(courseA2View4.getLeft(), y - courseA2ImageView4.getHeight(), courseA2View4.getRight(), y));
                        regionList.add(courseA2Module);
                        regionList.add(courseA2Module1);
                        regionList.add(courseA2Module2);
                        regionList.add(courseA2Module3);
                        moveList.add(false);
                        moveList.add(false);
                        moveList.add(false);
                        moveList.add(false);
                        RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(courseA2View1.getRight() - courseA2View1.getLeft(), (HEIGHT + courseA2ImageView1.getHeight() + HEIGHT));
                        RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(courseA2View2.getRight() - courseA2View2.getLeft(), (HEIGHT + courseA2ImageView2.getHeight() + HEIGHT));
                        RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(courseA2View3.getRight() - courseA2View3.getLeft(), (HEIGHT + courseA2ImageView3.getHeight() + HEIGHT));
                        RelativeLayout.LayoutParams layoutParams4 = new RelativeLayout.LayoutParams(courseA2View4.getRight() - courseA2View4.getLeft(), (HEIGHT + courseA2ImageView4.getHeight() + HEIGHT));

                        layoutParams1.topMargin = y - courseA2ImageView1.getHeight();
                        layoutParams1.leftMargin = courseA2View1.getLeft();
                        layoutParams2.topMargin = y - courseA2ImageView2.getHeight();
                        layoutParams2.leftMargin = courseA2View2.getLeft();
                        layoutParams3.topMargin = y - courseA2ImageView3.getHeight();
                        layoutParams3.leftMargin = courseA2View3.getLeft();
                        layoutParams4.topMargin = y - courseA2ImageView4.getHeight();
                        layoutParams4.leftMargin = courseA2View4.getLeft();

                        courseA2Shape1.setLayoutParams(layoutParams1);
                        courseA2Shape2.setLayoutParams(layoutParams2);
                        courseA2Shape3.setLayoutParams(layoutParams3);
                        courseA2Shape4.setLayoutParams(layoutParams4);

                        courseA2PDFView1.setVisibility(View.GONE);
                        courseA2PDFView.setTerminate(true);
                        courseA2PDFView.invalidate();
                    } else {
                        if (oldIndex == 3) {
                            reduction();
                        }
                        courseA2PDFView.setTerminate(false);
                        courseA2PDFView.invalidate();
                        courseA2PDFView1.setVisibility(View.VISIBLE);
                        int y = courseA2PDFView.getTop() + courseA2ImageView1.getHeight() - layoutHelper.scaleDimension(40, "y");
                        int y1 = courseA2PDFView1.getTop() + courseA2ImageView1.getHeight() - layoutHelper.scaleDimension(40, "y");
                        Region region = new Region(courseA2View1.getRight() - WIDTH, y - courseA2ImageView1.getHeight(), courseA2View1.getRight() + courseA2ImageView1.getWidth(), y + HEIGHT * 2);
                        Region region1 = new Region(courseA2View3.getRight() - WIDTH, y - courseA2ImageView2.getHeight(), courseA2View3.getRight() + courseA2ImageView3.getWidth(), y + HEIGHT * 2);
                        Region region2 = new Region(courseA2View1.getRight() - WIDTH, y1 - courseA2ImageView3.getHeight(), courseA2View1.getRight() + courseA2ImageView1.getWidth(), y1 + HEIGHT * 2);
                        Region region3 = new Region(courseA2View3.getRight() - WIDTH, y1 - courseA2ImageView4.getHeight(), courseA2View3.getRight() + courseA2ImageView3.getWidth(), y1 + HEIGHT * 2);

                        CourseA2Module courseA2Module = new CourseA2Module(region, new RectF(courseA2View1.getRight(), y - courseA2ImageView1.getHeight(), courseA2View1.getRight() + courseA2ImageView1.getWidth(), y));
                        CourseA2Module courseA2Module1 = new CourseA2Module(region1, new RectF(courseA2View3.getRight(), y - courseA2ImageView2.getHeight(), courseA2View3.getRight() + courseA2ImageView3.getWidth(), y));
                        CourseA2Module courseA2Module2 = new CourseA2Module(region2, new RectF(courseA2View1.getRight(), y1 - courseA2ImageView3.getHeight(), courseA2View1.getRight() + courseA2ImageView1.getWidth(), y1));
                        CourseA2Module courseA2Module3 = new CourseA2Module(region3, new RectF(courseA2View3.getRight(), y1 - courseA2ImageView4.getHeight(), courseA2View3.getRight() + courseA2ImageView3.getWidth(), y1));
                        regionList.add(courseA2Module);
                        regionList.add(courseA2Module1);
                        regionList.add(courseA2Module2);
                        regionList.add(courseA2Module3);
                        moveList.add(false);
                        moveList.add(false);
                        moveList.add(false);
                        moveList.add(false);


                        RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(courseA2ImageView1.getWidth() + WIDTH, (HEIGHT + courseA2ImageView1.getHeight() + HEIGHT));
                        RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(courseA2ImageView3.getWidth() + WIDTH, (HEIGHT + courseA2ImageView2.getHeight() + HEIGHT));
                        RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(courseA2ImageView1.getWidth() + WIDTH, (HEIGHT + courseA2ImageView3.getHeight() + HEIGHT));
                        RelativeLayout.LayoutParams layoutParams4 = new RelativeLayout.LayoutParams(courseA2ImageView3.getWidth() + WIDTH, (HEIGHT + courseA2ImageView4.getHeight() + HEIGHT));

                        layoutParams1.topMargin = y - courseA2ImageView1.getHeight();
                        layoutParams1.leftMargin = courseA2View1.getRight() - WIDTH;
                        layoutParams2.topMargin = y - courseA2ImageView2.getHeight();
                        layoutParams2.leftMargin = courseA2View3.getRight() - WIDTH;
                        layoutParams3.topMargin = y1 - courseA2ImageView3.getHeight();
                        layoutParams3.leftMargin = courseA2View1.getRight() - WIDTH;
                        layoutParams4.topMargin = y1 - courseA2ImageView4.getHeight();
                        layoutParams4.leftMargin = courseA2View3.getRight() - WIDTH;

                        courseA2Shape1.setLayoutParams(layoutParams1);
                        courseA2Shape2.setLayoutParams(layoutParams2);
                        courseA2Shape3.setLayoutParams(layoutParams3);
                        courseA2Shape4.setLayoutParams(layoutParams4);
                    }
                    oldIndex = index;
                }
            }
        });
    }

    private void reduction() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) courseA2ImageView1.getLayoutParams();
        layoutParams.topMargin = courseA2View1.getTop();
        layoutParams.leftMargin = courseA2View1.getLeft();
        RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) courseA2ImageView2.getLayoutParams();
        layoutParams1.topMargin = courseA2View2.getTop();
        layoutParams1.leftMargin = courseA2View2.getLeft();
        RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) courseA2ImageView3.getLayoutParams();
        layoutParams2.topMargin = courseA2View3.getTop();
        layoutParams2.leftMargin = courseA2View3.getLeft();
        RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) courseA2ImageView4.getLayoutParams();
        layoutParams3.topMargin = courseA2View4.getTop();
        layoutParams3.leftMargin = courseA2View4.getLeft();
    }

    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (mediaIndex >= testModule.getMp3UrlList().size() || v.getId() == R.id.courseA2FlatSharp) {
                switch (v.getId()) {
                    case R.id.courseA2FlatSharp:
                        showFlatSharpDialog(courseA2FlatSharp, true);
                        break;
                    case R.id.titleLayoutNextTextView:
                        next();
                        break;
                    case R.id.titleLayoutLastTextView:
                        last();
                        break;
                    case R.id.titleLayoutNumberRl:
                        skip();
                        break;
                    default:
                        break;
                }
            } else {
                if (answerPosition != 0) {
                    //答完题目
                    viewId = v.getId();
                    showDialog();
                } else {
                    Constant.showTextToast(activity, "答完本题后方可进入下一题");
                }
            }
        }

    }

    private void next() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);
        mediaPlayerStop();
    }

    private void last() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);
        mediaPlayerStop();
    }

    private void skip() {
        dialogShowListener.dialogShow(1, courseIndex, resultMap());
        dialogShowListener.dialogShow(0, courseIndex, resultMap());
        mediaPlayerStop();
    }

    private boolean resultMap() {
        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1),SPUtil.getSharedPreferencesData(activity, "number")+"_"+ (courseIndex + 1));

        score = 0;
        for (int i = 0; i < answerModuleList.size(); i++) {
            String mapValue = map.get(i + "");
            if (mapValue != null)
                if (mapValue.equals(answerModuleList.get(i).getId())) {
                    score += Double.valueOf(answerModuleList.get(i).getScore());
                }
        }
        LogUtil.i(TAG, "score=" + score);
        SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA2.class.getSimpleName(), score + "");
        return answerPosition != 0;
    }

    private void showDialog() {
        if (courseDialog == null) {
            String txt = activity.getResources().getString(R.string.courseText);
            courseDialog = new CourseDialog(activity, R.style.BlueToothDialogStyle, txt);
        }
        if (!courseDialog.isShowing()) {
            courseDialog.show();
        }
        courseDialog.setCourseDialogInterlisteren(new CourseDialog.CourseDialogListener() {
            @Override
            public void courseDialogResult(int type) {
                if (type == 1) {
                    mediaIndex = testModule.getMp3UrlList().size();
                    if (viewId == R.id.titleLayoutNextTextView) {
                        next();
                    } else if (viewId == R.id.titleLayoutLastTextView) {
                        last();
                    } else if (viewId == R.id.titleLayoutNumberRl) {
                        skip();
                    }
                }
            }
        });
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {
        mediaPlayerStop();
    }

    @Override
    public void destroy() {
        if (mHandler != null) {
            mHandler.removeCallbacks(updateThread);
        }
        mediaRelease();
        if (backtabAnimation != null) {
            backtabAnimation = null;
        }
    }

    private void mediaPlayerPlay() {
        try {
            mediaPlayer.reset();
            LogUtil.i(TAG, RetrofitClient.BASE_URL + testModule.getMp3UrlList().get(mediaIndex).getMp3Url());
            mediaPlayer.setDataSource(activity.getExternalFilesDir(null) + testModule.getMp3UrlList().get(mediaIndex).getMp3Url().replace("/", ""));
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    course1LayoutProgressBar.setMax(mp.getDuration());
                    mHandler.post(updateThread);
                    courseA2LayoutPlay.setImageResource(R.drawable.audio_pause_bg);
                    backtabAnimation = new AnimationDrawable();
                    backtabAnimation = (AnimationDrawable) courseA2LayoutPlay.getDrawable();
                    backtabAnimation.start();
                    LogUtil.i(TAG, "duration" + mp.getDuration());
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    try {
                        if (mediaIndex < testModule.getMp3UrlList().size()) {
                            LogUtil.i(TAG, "duration11  1" + mp.getDuration() + " stopIndex=" + stopIndex + " mediaIndex=" + mediaIndex + " RetrofitClient.BASE_URL + testModule.getMp3UrlList().get(mediaIndex).getMp3Url()=" + RetrofitClient.BASE_URL + testModule.getMp3UrlList().get(mediaIndex).getMp3Url());
                            stopIndex++;
                            if (stopIndex == Constant.MEDIA_PLAYER_STOP_NUMBER) {
                                mediaIndex++;
                                stopIndex = 0;
                            }
                            mp.reset();
                            if (mediaIndex == testModule.getMp3UrlList().size() || testModule.getMp3UrlList().get(mediaIndex).getMp3Url() == null) {
                                mediaIndex = testModule.getMp3UrlList().size();
                                mHandler.removeCallbacks(updateThread);
                                mediaRelease();
                                courseA2LayoutPlay.setImageResource(R.drawable.audio_play);
                                course1LayoutProgressBar.setProgress(0);
                            } else {
                                mp.setDataSource(activity.getExternalFilesDir(null) + testModule.getMp3UrlList().get(mediaIndex).getMp3Url().replace("/", ""));
                                mp.prepare();
                            }
                        } else {
                            mHandler.removeCallbacks(updateThread);
                            mediaRelease();
                            courseA2LayoutPlay.setImageResource(R.drawable.audio_play);
                            course1LayoutProgressBar.setProgress(0);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mediaRelease() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void mediaPlayerStop() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(updateThread);
        }
        if (backtabAnimation != null) {
            backtabAnimation.stop();
            courseA2LayoutPlay.setImageResource(R.drawable.audio_play);
        }
        if (course1LayoutProgressBar != null) {
            course1LayoutProgressBar.setProgress(0);
        }
    }

    /**
     * update进度条
     */
    private Runnable updateThread = new Runnable() {
        @Override
        public void run() {
            try {
                if (mediaPlayer != null) {
                    if (mediaPlayer.getCurrentPosition() == mediaPlayer.getDuration()) {
                        return;
                    }
                    course1LayoutProgressBar.setProgress(mediaPlayer.getCurrentPosition());
                }
                mHandler.removeCallbacks(updateThread);
                mHandler.postDelayed(updateThread, 50);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
